package Proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class dynamicAgency {
	public static void main(String[] args) throws IllegalAccessException, InstantiationException {
		System.setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
		UserService userServiceImpl = new UserServiceImpl();
		ClassLoader classLoader = userServiceImpl.getClass().getClassLoader();
		Class<?>[] interfaces = userServiceImpl.getClass().getInterfaces();
		InvocationHandler method_handler = new Method_Handler(userServiceImpl);
		UserService proxy =(UserService) Proxy.newProxyInstance(classLoader, interfaces, method_handler);
		proxy.select();
		proxy.update();
		
		// 保存JDK动态代理生成的代理类，类名保存为 UserServiceProxy
      // ProxyUtils.generateClassFile(userServiceImpl.getClass(), "UserServiceProxy");
		//获取指定代理对象所关联的调用处理器
		InvocationHandler h= Proxy.getInvocationHandler(proxy);
		System.out.println(h.toString());//代理学习.Method_Handler@5d3411d
		//指定接口的代理类
		//Class cls=Proxy.getProxyClass(classLoader, interfaces);
		//返回 cl 是否为一个代理类
		boolean bool=Proxy.isProxyClass(proxy.getClass());
		System.out.println(bool);//true
	}
}

class Method_Handler implements InvocationHandler {//调用处理器
	Object target; // 被代理的对象，实际的方法执行者

	public Method_Handler(Object target) {
		this.target = target;
	}

	Logger log = LoggerFactory.getLogger(getClass());

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		log.info("汉字start");
		Object result = method.invoke(target, args);
		log.info("end");
		return result;
	}

}
/*
14:43:03.543 [main] INFO 代理学习.Method_Handler -- start
查询 selectById
14:43:03.566 [main] INFO 代理学习.Method_Handler -- end
14:43:03.566 [main] INFO 代理学习.Method_Handler -- start
更新 update
14:43:03.567 [main] INFO 代理学习.Method_Handler -- end
*/